﻿#region

using System;
using System.Collections.Generic;
using System.Globalization;
using System.Linq;
using System.Web.UI;
using System.Web.UI.WebControls;
using BusinessLogicLayer;
using BusinessObjects;

#endregion

namespace FastTrackCabService.CustomerPanel
{
    public partial class ModifyBooking : Page
    {
        private static int _bookingId;

        protected void Page_Load(object sender, EventArgs e)
        {
            if (!string.IsNullOrEmpty(Request.QueryString["id"]))
            {
                if (IsPostBack) return;
                _bookingId = Convert.ToInt32(Request.QueryString["id"]);
                var districts = DistrictBLL.GetAllDistricts();
                ddlFromDistrict.DataTextField = "Name";
                ddlFromDistrict.DataValueField = "DistrictId";
                ddlFromDistrict.DataSource = districts;
                ddlFromDistrict.DataBind();
                LoadCities("ddlToDistrict");
                txtTravelDate.Text = DateTime.Now.ToShortDateString();
                LoadCarDdl();

                try
                {
                    int id = Convert.ToInt32(Request.QueryString["id"]);
                    string type = BookingBLL.GetBookingType(id);
                    string status;
                    if (type.Equals("PICK"))
                    {
                        PickBooking booking = PickBookingBLL.GetBooking(id);
                        ddlType.SelectedValue = booking.Type;
                        ddlVehicleNum.SelectedValue =
                            (booking.VehicleRequirement.NumberOfCars + booking.VehicleRequirement.NumberOfVans)
                                .ToString
                                ();
                        LoadCarDdl();
                        ddlCars.SelectedValue = booking.VehicleRequirement.NumberOfCars.ToString();
                        ddlVans.SelectedValue = booking.VehicleRequirement.NumberOfVans.ToString();
                        txtNameOrNum.Text = booking.OriginLocation.HomeNumberOrName;
                        txtStreet.Text = booking.OriginLocation.Street;
                        ddlFromDistrict.SelectedValue = booking.OriginLocation.DistrictId.ToString();
                        LoadCities("ddlFromDistrict");
                        List<City> fromCities =
                            CityBLL.GetAllCitiesByDistrictId(Convert.ToByte(booking.OriginLocation.DistrictId));

                        if (fromCities.Where(city => city.Name == booking.OriginLocation.City).ToList().Count > 0)
                        {
                            ddlFromCity.Items.Cast<ListItem>()
                                .Single(i => i.Text == booking.OriginLocation.City)
                                .Selected = true;
                        }
                        else
                        {
                            ddlFromCity.Items.Cast<ListItem>().Single(i => i.Text == "Other").Selected = true;
                            txtFromCity.Visible = true;
                            txtFromCity.Text = booking.OriginLocation.City;
                        }
                        List<City> toCities = CityBLL.GetAllCities();
                        if (toCities.Where(city => city.Name == booking.Destination).ToList().Count > 0)
                        {
                            ddlToCity.Items.Cast<ListItem>().Single(i => i.Text == booking.Destination).Selected = true;
                        }
                        else
                        {
                            ddlToCity.Items.Cast<ListItem>().Single(i => i.Text == booking.OriginLocation.City).Selected
                                = true;
                            txtToCity.Visible = true;
                            txtToCity.Text = booking.Destination;
                        }
                        txtTravelDate.Text = booking.OriginDateTime.ToShortDateString();
                        TravelCalendar.SelectedDate = booking.OriginDateTime;
                        ddlFromTimeHour.SelectedValue = booking.OriginDateTime.Hour.ToString();
                        ddlFromTimeMinute.SelectedValue = booking.OriginDateTime.Minute.ToString();
                        ddlFromAmPm.SelectedValue = booking.OriginDateTime.ToString("tt", CultureInfo.InvariantCulture);
                        status = booking.Status;
                    }
                    else
                    {
                        PickAndDropBooking booking = PickAndDropBookingBLL.GetBooking(id);
                        ddlType.SelectedValue = booking.Type;
                        ddlVehicleNum.SelectedValue =
                            (booking.VehicleRequirement.NumberOfCars + booking.VehicleRequirement.NumberOfVans)
                                .ToString
                                ();
                        LoadCarDdl();
                        ddlCars.SelectedValue = booking.VehicleRequirement.NumberOfCars.ToString();
                        ddlVans.SelectedValue = booking.VehicleRequirement.NumberOfVans.ToString();
                        txtNameOrNum.Text = booking.OriginLocation.HomeNumberOrName;
                        txtStreet.Text = booking.OriginLocation.Street;
                        ddlFromDistrict.SelectedValue = booking.OriginLocation.DistrictId.ToString();
                        List<City> fromCities =
                            CityBLL.GetAllCitiesByDistrictId(Convert.ToByte(booking.OriginLocation.DistrictId));
                        LoadCities("ddlFromDistrict");

                        if (fromCities.Where(city => city.Name == booking.OriginLocation.City).ToList().Count > 0)
                        {
                            ddlFromCity.Items.Cast<ListItem>()
                                .Single(i => i.Text == booking.OriginLocation.City)
                                .Selected = true;
                        }
                        else
                        {
                            ddlFromCity.Items.Cast<ListItem>().Single(i => i.Text == "Other").Selected = true;
                            txtFromCity.Visible = true;
                            txtFromCity.Text = booking.OriginLocation.City;
                        }
                        List<City> toCities = CityBLL.GetAllCities();
                        if (toCities.Where(city => city.Name == booking.MidPoint).ToList().Count > 0)
                        {
                            ddlToCity.Items.Cast<ListItem>().Single(i => i.Text == booking.MidPoint).Selected = true;
                        }
                        else
                        {
                            ddlToCity.Items.Cast<ListItem>().Single(i => i.Text == "Other").Selected = true;
                            txtToCity.Visible = true;
                            txtToCity.Text = booking.MidPoint;
                        }
                        txtTravelDate.Text = booking.OriginDateTime.ToShortDateString();
                        TravelCalendar.SelectedDate = booking.OriginDateTime;
                        ddlFromTimeHour.SelectedValue = booking.OriginDateTime.Hour.ToString();
                        ddlFromTimeMinute.SelectedValue = booking.OriginDateTime.Minute.ToString();
                        ddlFromAmPm.SelectedValue = booking.OriginDateTime.ToString("tt", CultureInfo.InvariantCulture);
                        status = booking.Status;
                    }
                    txtStatus.Text = status;
                    btnCancel.Visible = false;
                    btnUpdate.Visible = false;
                    if (status.Equals("Pending"))
                    {
                        btnCancel.Visible = true;
                        btnUpdate.Visible = true;
                    }
                    else if (status.Equals("Approved"))
                    {
                        btnCancel.Visible = true;
                    }
                }
                catch (Exception)
                {
                    Response.Redirect("Booking.aspx");
                }
            }
            else
            {
                Response.Redirect("Default.aspx");
            }
        }

        private void LoadCarDdl()
        {
            ddlCars.Items.Clear();
            for (var x = 0; x <= Convert.ToInt32(ddlVehicleNum.SelectedValue); x++)
            {
                ddlCars.Items.Add(new ListItem
                {
                    Text = x.ToString(),
                    Value = x.ToString()
                });
            }
            ddlCars.SelectedValue = ddlVehicleNum.SelectedValue;
            ddlVans.SelectedValue = "0";
        }

        protected void btnTravelCalender_OnClick(object sender, EventArgs e)
        {
            TravelCalendar.Visible = !TravelCalendar.Visible;
        }

        protected void TravelCalendar_OnSelectionChanged(object sender, EventArgs e)
        {
            txtTravelDate.Text = TravelCalendar.SelectedDate.ToShortDateString();
            TravelCalendar.Visible = false;
        }

        protected void ddlFromDistrict_OnSelectedIndexChanged(object sender, EventArgs e)
        {
            LoadCities("ddlFromDistrict");
            txtFromCity.Text = "";
            txtFromCity.Visible = false;
        }

        private void LoadCities(string id)
        {
            if (id.Equals("ddlFromDistrict"))
            {
                ddlFromCity.Items.Clear();
                var cities = CityBLL.GetAllCitiesByDistrictId(Convert.ToByte(ddlFromDistrict.SelectedValue));
                ddlFromCity.DataTextField = "Name";
                ddlFromCity.DataValueField = "CityId";
                ddlFromCity.DataSource = cities;
                ddlFromCity.DataBind();
                ddlFromCity.Items.Add(new ListItem
                {
                    Text = "Other",
                    Value = "Other"
                });
            }
            else if (id.Equals("ddlToDistrict"))
            {
                ddlToCity.Items.Clear();
                var cities = CityBLL.GetAllCities();
                ddlToCity.DataTextField = "Name";
                ddlToCity.DataValueField = "CityId";
                ddlToCity.DataSource = cities;
                ddlToCity.DataBind();
                ddlToCity.Items.Add(new ListItem
                {
                    Text = "Other",
                    Value = "Other"
                });
            }
        }

        protected void ddlFromCity_OnSelectedIndexChanged(object sender, EventArgs e)
        {
            txtFromCity.Visible = ddlFromCity.SelectedValue.Equals("Other");
            if (txtFromCity.Visible) txtFromCity.Text = "";
        }

        protected void ddlToCity_OnSelectedIndexChanged(object sender, EventArgs e)
        {
            txtToCity.Visible = ddlToCity.SelectedValue.Equals("Other");
            if (txtToCity.Visible) txtToCity.Text = "";
        }

        protected void btnUpdate_OnClick(object sender, EventArgs e)
        {
            if (Page.IsValid)
            {
                try
                {
                    var originTime = Convert.ToDateTime(txtTravelDate.Text + " " + ddlFromTimeHour.SelectedValue +
                                                        ":" + ddlFromTimeMinute.SelectedValue + " " +
                                                        ddlFromAmPm.SelectedValue);
                    if (ddlType.SelectedValue.Equals("PICK"))
                    {
                        var booking = new PickBooking
                        {
                            BookingId = _bookingId,
                            OriginDateTime = originTime,
                            Destination = (txtToCity.Visible) ? txtToCity.Text : ddlToCity.SelectedItem.Text
                        };
                        var location = new CurrentLocation
                        {
                            HomeNumberOrName = txtNameOrNum.Text,
                            Street = txtStreet.Text,
                            City = (txtFromCity.Visible) ? txtFromCity.Text : ddlFromCity.SelectedItem.Text,
                            DistrictId = Convert.ToInt32(ddlFromDistrict.SelectedValue)
                        };
                        var vehicleRequirement = new BookingVehicleRequirement
                        {
                            NumberOfCars = Convert.ToInt32(ddlCars.SelectedValue),
                            NumberOfVans = Convert.ToInt32(ddlVans.SelectedValue)
                        };
                        booking.OriginLocation = location;
                        booking.VehicleRequirement = vehicleRequirement;
                        PickBookingBLL.UpdatePickBooking(booking);
                    }
                    else
                    {
                        var booking = new PickAndDropBooking
                        {
                            BookingId = _bookingId,
                            OriginDateTime = originTime,
                            MidPoint = (txtToCity.Visible) ? txtToCity.Text : ddlToCity.SelectedItem.Text
                        };
                        var location = new CurrentLocation
                        {
                            HomeNumberOrName = txtNameOrNum.Text,
                            Street = txtStreet.Text,
                            City = (txtFromCity.Visible) ? txtFromCity.Text : ddlFromCity.SelectedItem.Text,
                            DistrictId = Convert.ToInt32(ddlFromDistrict.SelectedValue)
                        };
                        var vehicleRequirement = new BookingVehicleRequirement
                        {
                            NumberOfCars = Convert.ToInt32(ddlCars.SelectedValue),
                            NumberOfVans = Convert.ToInt32(ddlVans.SelectedValue)
                        };
                        booking.OriginLocation = location;
                        booking.VehicleRequirement = vehicleRequirement;
                        PickAndDropBookingBLL.UpdatePickAndDropBooking(booking);
                    }
                    Response.Redirect("ModifyBooking.aspx?id=" + _bookingId, false);
                }
                catch
                {
                    Response.Redirect("Booking.aspx");
                }
            }
        }

        protected void CustomValidatorFromCity_OnServerValidate(object source, ServerValidateEventArgs args)
        {
            if ((!txtFromCity.Visible) || (txtFromCity.Visible && (!string.IsNullOrEmpty(txtFromCity.Text))))
            {
                args.IsValid = true;
            }
            else
            {
                args.IsValid = false;
                txtFromCity.Focus();
            }
        }

        protected void TravelCalendar_OnDayRender(object sender, DayRenderEventArgs e)
        {
            if (txtTravelDate.Text != "")
            {
                if (e.Day.Date < DateTime.Now.AddDays(-1) || e.Day.Date > DateTime.Now.AddDays(7))
                {
                    e.Day.IsSelectable = false;
                }
            }
        }

        protected void ddlVehicleNum_OnSelectedIndexChanged(object sender, EventArgs e)
        {
            LoadCarDdl();
        }

        protected void ddlCars_OnSelectedIndexChanged(object sender, EventArgs e)
        {
            ddlVans.SelectedValue =
                (Convert.ToInt32(ddlVehicleNum.SelectedValue) - Convert.ToInt32(ddlCars.SelectedValue)).ToString();
        }

        protected void CustomValidatorToCity_OnServerValidate(object source, ServerValidateEventArgs args)
        {
            if ((!txtToCity.Visible) || (txtToCity.Visible && (!string.IsNullOrEmpty(txtToCity.Text))))
            {
                args.IsValid = true;
            }
            else
            {
                args.IsValid = false;
                txtToCity.Focus();
            }
        }

        protected void btnCancel_OnClick(object sender, EventArgs e)
        {
            BookingBLL.ChangeStatus(_bookingId, "Cancelled");
            Response.Redirect("ModifyBooking.aspx?id=" + _bookingId, false);
        }
    }
}